<template>
  <div class="shop_info">
    <!-- 法人信息 -->
    <van-form @submit="onSubmit" error-message-align="right" input-align="right">
      <!-- :rules="[{ required: true, message: '不能为空' }]" -->
      <van-field name="license_url" label="" label-width="4rem" >
        <template #label>
          <div class="shop_upload_text">
            <div>上传开户许可证</div>
            <div>保证照片清晰可见</div>
            <div @click="getExample('merchant_business_license')">查看示例</div>
          </div>
        </template>
        <template #input>
          <van-uploader v-model="license_url" :max-count="1" :after-read="afterReadLicense"
            :before-delete="uploadDleteLicense">
            <img src="../../../../images/mine/icon_tup.png" alt="" class="shop_upload_img">
          </van-uploader>
        </template>
      </van-field>
      <!--  :rules="[{ required: true, message: '请输入开户银行名称' }]" -->
      <van-field v-model="bank_name" name="bank_name" label="开户银行" placeholder="请输入开户银行名称"
        />
      <!-- <van-field v-model="branch_name" name="branch_name" label="开户支行名称" placeholder="请输入开户支行名称"
                :rules="[{ required: true, message: '请输入开户支行名称' }]" /> -->
      <div class="search-container">
        <!-- :rules="[{ required: true, message: '请输入开户支行' }]"  -->
        <van-field v-model="branch_name" placeholder="请输入支行" @input="debouncedSearch" :loading="isLoading"
          name="branch_name" autocomplete="off" label="开户支行" />
        <div class="custom-dropdown" v-show="showDropdown">
          <div v-for="item in searchResults" :key="item.value" class="dropdown-item" @click="onSelect(item)">
            {{ item.text }}
          </div>
        </div>
      </div>
<!--  :rules="[{ required: true, message: '请输入对公银行账号' }]"  -->
      <van-field v-model="account" name="account" label="对公银行账号" placeholder="请输入对公银行账号"
       />
      <van-field v-model="region_name" name="region_name" readonly label="开户地区" is-link placeholder="请选择"
        @click="showPopup = true" class="van-cell--clickable" />
      <!-- <van-field
        v-model="password"
        name="password"
        label="设置登录密码"
        placeholder="请输入商家登录密码"

      /> -->
      <div style="width: 100%">
        <!-- <van-button round block type="default" @click="backBtn"style="width: 95%;margin: 0.32rem auto;"
        >上一步</van-button> position: fixed;bottom: 0; -->
        <van-button round block type="info" native-type="submit" style="width: 95%;margin: 0.32rem auto;border-radius: 0.44rem"
          color="linear-gradient( 136deg, #6EC069 0%, #42A633 100%)"
          v-if="info.status == -1 || info.status == 0 || info.status == 20">提交</van-button>
      </div>
    </van-form>
    <van-button round block type="info" @click="onDraft" style="width: 95%;margin: 0.32rem auto;border-radius: 0.44rem" v-if="info.id <= 0"
      color="linear-gradient( 136deg, #6EC069 0%, #42A633 100%)">暂存草稿</van-button>
    <van-popup v-model="showExaplePopup" :style="{ width: '80%' }">
      <div class="popup_example">
        <img :src="example.content" alt="">
        <div>{{ example.tip_msg }}</div>
      </div>
    </van-popup>

    <!-- 省市区 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-cascader v-model="cascaderValue" title="请选择地址" :options="options" @close="showPopup = false"
        @change="onChange" @finish="onFinish" active-color="#31A653"/>
    </van-popup>
  </div>
</template>
<script>
import { BANK_BRANCH, OCR_RECOGNIZE, CACHE_COMMIT, CACHE_INFO } from '@/api/mine'
import { getOssParams, uploadImage, uploadDelete, getExampleList } from '@/api/upload';
import { REGION_LIST } from "@/api/home";
import { setImageUrl, getImageUrl } from '@/api/upload'; // Adjust the path accordingly
export default {
  props: ['info'],
  data() {
    return {
      selectAreaList: [], // 已选中地区
      showPopup: false,
      cascaderValue: "",
      sbumitShow: false,
      options: [],
      region_name: '',
      region_code: '',
      account: "",
      password: "",
      bank_name: "",
      branch_name: "",
      searchResults: [],
      license_url: [],
      valueArray: [],
      isLoading: false,
      showDropdown: false,
      showExaplePopup: false,
      example: {

      }
    };
  },
  created() {
    this.debouncedSearch = this.debounce(this.onSearch, 300);
  },
  mounted() {
    //  setTimeout(()=>{
    this.fetchRegions(1, 0);
    this.getInfo()

  },
  watch: {
    branch_name(value) {
      if (value.length === 0) {
        this.searchResults = [];
        this.showDropdown = false;
      }
    },
  },
  methods: {
    async getInfo() {
      if (this.info.id <= 0) {
        let params = {
          type: 'shop',
          key: 'bankInfo',

        }
        this.$http.get(CACHE_INFO, { params: params }).then(res => {
          if (res.data.content != '') {
            const data = JSON.parse(res.data.content);
            // 回显数据
            this.license_url = setImageUrl(data.license_url)
            this.region_code = data.region_code;
            this.region_name = data.region_name;
            this.bank_name = data.bank_name;
            this.branch_name = data.branch_name;
            this.password = data.password
            //   this.account = this.settle.account_data.account;
            this.account = data.account
            if (this.info.account_data.city_code != 0) {
              this.fetchRegions(this.info.account_data.province_code, 1);
              this.fetchRegions(this.info.account_data.city_code, 2);
              this.fetchRegions(this.info.account_data.county_code, 3);
            }
            this.cascaderValue = data.region_code;
          }
        })
      } else {
        this.license_url = this.info.account_data.license_url == '' ? [] : [{ url: this.info.account_data.license_url }];
        this.region_code = this.info.account_data.region_code;
        this.region_name = this.info.account_data.region_name;
        this.bank_name = this.info.account_data.bank_name;
        this.branch_name = this.info.account_data.branch_name;
        this.password = this.info.password
        //   this.account = this.settle.account_data.account;
        this.account = this.info.account_data.account;
        if (this.info.account_data.city_code != 0) {
          await this.fetchRegions(this.info.account_data.province_code, 1);
          await this.fetchRegions(this.info.account_data.city_code, 2);
          await this.fetchRegions(this.info.account_data.county_code, 3);
        }
        this.cascaderValue = this.info.account_data.region_code;
      }
    },
    async getExample(key) {
      this.example = await getExampleList(this.$http, key)
      this.showExaplePopup = true
    },
    // 上传营业执照
    async afterReadLicense(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http, this.$http);
        }
        if (!this.ossParams) {
          throw new Error('OSS参数未正确设置');
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.license_url);
        let params = {
          type: "bank_account_license",
          image_url: this.license_url.map((item) => item.url)[0],
          //   face: true,
        };
        this.$http.post(OCR_RECOGNIZE, params).then((res) => {

          this.bank_name = res.data.bank_account_license.depositary_bank;
          //   this.bank_code=res.data.bank_card.bank_code
          this.account = res.data.bank_account_license.bank_account;
        });
      } catch (error) {
        console.error("处理上传错误:", error);
      }
    },
    // 删除营业执照
    uploadDleteLicense(file) {
      this.license_url = uploadDelete(file, this.license_url);
      this.business_license = {}
    },
    async onSearch() {
      if (this.branch_name.length > 0) {
        this.isLoading = true;
        try {
          const results = await this.mockRemoteSearch(this.branch_name);
          this.searchResults = results.map((item) => ({
            text: item.name,
            value: item.id,
          }));
          this.showDropdown = this.searchResults.length > 0;
        } catch (error) {
          console.error("搜索出错:", error);
        } finally {
          this.isLoading = false;
        }
      } else {
        this.searchResults = [];
        this.showDropdown = false;
      }
    },
    async mockRemoteSearch(keyword) {
      await new Promise((resolve) => setTimeout(resolve, 300));
      const response = await this.$http.get(BANK_BRANCH, { params: { name: keyword, limit: 10 } });
      const allItems = response.data; // 获取接口返回的数据

      return allItems.filter((item) => item.name.includes(keyword));
    },
    onSelect(item) {
      this.branch_name = item.text;
      this.showDropdown = false;
    },
    debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    },
    // 选择器变化时的回调
    onChange(res) {
      this.tabIndex = res.tabIndex;
      if (this.tabIndex === 3) {
        return;
      }
      //   console.log(res, "jj");
      //点击加载下一级回调
      this.getSpaceListAgain(res.selectedOptions, res.value);
    },
    getSpaceListAgain(selectedOptions, value) {
      this.$http
        .get(REGION_LIST, {
          params: {
            code: value,
          },
        })
        .then((res) => {
          let { data } = res;

          if (this.tabIndex == 2 && !data.length) {
            data = [{
              code: 0,
              name: '暂不选择',
              parent_code: value
            }]
          }

          if (data && data.length) {
            this.setOptions(selectedOptions, data);
          }
        });
    },
    setOptions(selectedOptions, data) {
      let _options = this.options;
      selectedOptions.forEach((item, index) => {
        if (index) {
          //不是第一个则取下一级children
          _options = _options.children;
        }
        _options =
          _options[_options.findIndex((_item) => _item.value === item.value)];
      });
      //找到最后一级
      _options.children = data.map((item) => {
        return {
          text: item.name,
          value: item.code,
          children: this.tabIndex == 2 ? null : [],
        };
      });
    },
    // 确定省市区
    onFinish({ selectedOptions }) {
      this.showPopup = false;
      this.selectAreaList = selectedOptions;
      let selectArea = selectedOptions.filter((item) => item.value !== 0);
      this.valueArray = selectArea.map((item) => item.value);
      this.region_code = this.valueArray.slice(-1)[0]
      selectedOptions = selectedOptions.filter((item) => {
        return item.value !== 0;
      });

      this.region_name = selectedOptions.map((option) => option.text).join("/");
    },
    async fetchRegions(parentCode, level) {
      const res = await this.$http.get(REGION_LIST, {
        params: {
          code: parentCode,
        },
      });
      let { data } = res;
      if (level == 3 && !data.length) {
        data = [{
          name: '暂无选择',
          code: 0,
          parent_code: parentCode
        }]
      }

      // 省级
      if (level === 0) {
        data.forEach((item) => {
          this.options.push({
            text: item.name,
            value: item.code,
            children: [],
          });
        });
      } else if (level === 1) {
        // 市级数据
        const province = this.options.find((item) => item.value === parentCode);
        if (province) {
          province.children = data.map((item) => ({
            text: item.name,
            value: item.code,
            children: [],
          }));
        }
      } else if (level === 2) {
        // 区/县级数据
        this.options.forEach((province) => {
          const city = province.children.find(
            (item) => item.value === parentCode
          );
          if (city) {
            city.children = data.map((item) => ({
              text: item.name,
              value: item.code,
              children: [],
            }));
          }
        });
      } else if (level === 3) {
        // 街道数据
        this.options.forEach((province) => {
          province.children.forEach((city) => {
            const county = city.children.find(
              (item) => item.value === parentCode
            );
            if (county) {
              county.children = data.map((item) => ({
                text: item.name,
                value: item.code,
              }));
            }
          });
        });
      }
    },
    onSubmit(values) {
      //   console.log("submit", values);
      this.sbumitShow = true;
      let data = {
        region_name: this.region_name,
        region_code: this.region_code,
      }
      let datas = {
        license_url: getImageUrl(this.license_url),
        region_code: this.region_code,
        region_name: this.region_name,
        bank_name: this.bank_name,
        branch_name: this.branch_name,
        password: this.password,
        account: this.account,
        cascaderValue: this.region_code
      }
      let params = {
        type: 'shop',
        key: 'bankInfo',
        content: JSON.stringify(datas)
      }
      if(this.info.id<=0){
      this.$http.post(CACHE_COMMIT, params).then(res => {
      })
    }
      this.$emit("bankCard", this.valueArray, values, data);
    },
    onDraft() {
      let params = {
        license_url: getImageUrl(this.license_url),
        region_code: this.region_code,
        region_name: this.region_name,
        bank_name: this.bank_name,
        branch_name: this.branch_name,
        password: this.password,
        account: this.account,
        cascaderValue: this.region_code
      }
      let data = {
        type: 'shop',
        key: 'bankInfo',
        content: JSON.stringify(params)
      }
      this.$http.post(CACHE_COMMIT, data).then(res => {
        this.$toast('暂存成功')
      })
    },
    backBtn() {
      this.$emit("goBack", 2)
    }
  },
};
</script>
<style scoped lang="scss">
::v-deep .van-cell {
  background: transparent;
}

.search-container {
  position: relative;
  z-index: 10;
}

.custom-dropdown {
  position: absolute;
  width: auto;
  max-height: 4rem;
  overflow: auto;
  top: 100%;
  right: 10px;
  font-size: 0.24rem;
  background-color: #fff;
  border: 1px solid #dcdee0;
  border-radius: 5px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.12);
}

.dropdown-item {
  padding: 10px 12px;
  cursor: pointer;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.dropdown-item:hover::after {
  border-color: transparent transparent red transparent;
  /* 悬停时三角形颜色 */
}

.dropdown-item:hover {
  // color: red;
}

.shop_upload_text {
  // line-height: 0.5rem;
  line-height: .6rem;
  text-align: left;
  font-style: normal;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;

  div:nth-child(1) {
    // font-weight: 400;
    font-size: .28rem;
    color: #333333;

  }

  div:nth-child(2) {
    font-size: .24rem;
    color: #999999;
  }

  div:nth-child(3) {
    font-size: 0.24rem;
    color: #31A653;
  }
}

.popup_example {
  padding-bottom: 0.2rem;

  img {
    width: 100%;
  }

  div {
    padding: 0 .12rem;
    box-sizing: border-box;
    font-size: 0.28rem;
  }

}

.van-cell--clickable {
  ::v-deep .van-icon {
    color: #969799 !important;
  }
}

.shop_upload_img {
  width: 0.64rem;
  height: 0.64rem;
  margin-top: 70%;
}
</style>
